package com.hymjweb.demo.framework.download;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.hymjweb.demo.framework.cache.service.GlobalCacheService;
import com.hymjweb.demo.framework.sys.BaseService;
import com.hymjweb.demo.framework.util.DataTypeUtil;
import com.hymjweb.demo.framework.util.DateUtil;
import com.hymjweb.demo.framework.util.HttpClientUtil;
import com.hymjweb.demo.framework.util.StringUtil;
import com.hymjweb.demo.framework.util.util.PoiUtil;
import lombok.val;
import org.beetl.ext.fn.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @BelongsProject: demo
 * @BelongsPackage: com.hymjweb.demo.framework.download
 * @Author: luoge
 * @CreateTime: 2020-09-30 14:16
 * @Description:
 */

@Service
public class DownloadService extends BaseService {

    private static Logger logger = LoggerFactory.getLogger(DownloadService.class);

    private static final String KEY_TITLE = "title";

    private static final String KEY_FIELD = "field";

    private static final String CACHE_KEY = "cacheKey";

    @Autowired
    private GlobalCacheService globalCacheService;



    /**
     * json对象转为Java对象
     * @param columnList
     * @return
     */
    public List<DownloadBean> columnDataConvertToJavaObjct(Object columnList) {
        if(columnList == null){
            return  null;
        }

        String columnJsonStr= DataTypeUtil.toNotNullString(columnList);

        if(StringUtils.isEmpty(columnJsonStr)){
            return null;
        }

        JSONArray columnJsonArray = JSONArray.parseArray(columnJsonStr);

        List<DownloadBean> downloadBeans=new ArrayList<>();

        for(int i=0;i<columnJsonArray.size();i++){
            JSONObject object= (JSONObject) columnJsonArray.get(i);
            DownloadBean downloadBean=JSONObject.toJavaObject(object,DownloadBean.class);
            downloadBeans.add(downloadBean);
        }

        return downloadBeans;

    }

    public String sendRequest(String url, String params) throws Exception {
        return  HttpClientUtil.getInstance().sendFormHttpPost(url,params,false);
    }


    public File createExcel(String tempFilePath, String fileName, String miniUiGridDataJsonStr, List<DownloadBean> downloadBeans) throws Exception {

        HashMap<String ,String[]> dataMap=getAllData2Map(downloadBeans);
        String[] titles = dataMap.get(KEY_TITLE);
        String[] fields = dataMap.get(KEY_FIELD);
        String[] cacheKeys = dataMap.get(CACHE_KEY);


        JSONObject object= JSONObject.parseObject(miniUiGridDataJsonStr);


        Map<String,Object> map=object.toJavaObject(new TypeReference<Map<String,Object>>(){});

        List rows = (List)map.get("data");
        List<Object[]> rowList=new ArrayList<>();

        HashMap<String, String> tempCacheMap = new HashMap<String, String>();
        for(int i=0;i<rows.size();i++){
            Map<String,Object> row= (Map<String, Object>) rows.get(i);
            Object[] obj=getArrayFromMap(row,fields,cacheKeys,tempCacheMap);
            rowList.add(obj);
        }

        tempCacheMap.clear();

        Object[][] objects= rowList.toArray(new Object[0][0]);

        String czyId=this.getLoginCzyId();

        return PoiUtil.createExcel(tempFilePath + czyId + fileName, "Sheet", titles, objects);

    }

    private Object[] getArrayFromMap(Map row, String[] fields, String[] cacheKeys, HashMap<String, String> tempCacheMap) {
        String[] rowData=new String[fields.length];
        for(int i=0;i<fields.length;i++){
            String fieldId=fields[i];
            String cacheKey=cacheKeys[i];
            String cellValue=DataTypeUtil.toNotNullString(row.get(fieldId));
            if(!DataTypeUtil.isEmptyStr(cacheKey)){
                cellValue=getCacheValueByKeyAndId(cacheKey,cellValue,tempCacheMap);
            }else{
                if(DateUtil.isValidDate(cellValue) && cellValue.contains("-")){
                    cellValue=DateUtil.changeStrDate(cellValue,"yyyy-MM-dd");
                }
            }
            rowData[i]=cellValue;
        }

        return rowData;

    }

    private String getCacheValueByKeyAndId(String cacheKey, String cellValue, HashMap<String, String> tempCacheMap) {
        String value="";
        if(DataTypeUtil.isEmptyStr(cellValue)){
            return value;
        }

        // cacheKey = "sysDic"
        //cellValue = "661,662,663"

        String tempKey = cacheKey + "," + cellValue;
        if(!tempCacheMap.containsKey(tempKey)){
            if(cellValue.contains(",")){
                String[] cellValueArray = cellValue.split(",");
                for(int i=0;i<cellValueArray.length;i++){
                    value += globalCacheService.getNameByCacheNameAndId(cacheKey,cellValueArray[i]) + ",";
                }
                value = value.substring(0,value.length()-1);
            }
            else{
                value = globalCacheService.getNameByCacheNameAndId(cacheKey,cellValue);
            }
            tempCacheMap.put(tempKey,value);
        }
        else{
            value = tempCacheMap.get(tempKey);
        }

        return value;
    }

    private HashMap<String, String[]> getAllData2Map(List<DownloadBean> downloadBeans) {
        HashMap<String, String[]> map = new HashMap<String, String[]>();
        List<String> listTitle = new ArrayList<String>();
        List<String> listField = new ArrayList<String>();
        List<String> listCacheKey = new ArrayList<String>();

        for(int i=0;i<downloadBeans.size();i++){
            String title = downloadBeans.get(i).getHeader();
            String field = downloadBeans.get(i).getField();
            String cacheKey=downloadBeans.get(i).getCacheName();
            title=DataTypeUtil.refineMessage(title);
            if (DataTypeUtil.isEmptyStr(title)) {
                continue;
            }
            listTitle.add(title);
            listField.add(field);
            listCacheKey.add(cacheKey);
        }
        map.put(KEY_TITLE, listTitle.toArray(new String[0]));
        map.put(KEY_FIELD, listField.toArray(new String[0]));
        map.put(CACHE_KEY, listCacheKey.toArray(new String[0]));
        return map;
    }
}
